package com.fr.data.core.db.dml;

import com.fr.base.FRContext;
import com.fr.base.core.util.TemplateUtils;
import com.fr.data.core.db.DBUtils;
import com.fr.data.core.db.dialect.Dialect;
import com.fr.data.core.db.dialect.DialectFactory;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;

public class Delete extends AbstractDML
{
  private Where where;

  public Delete(Table paramTable)
  {
    this(paramTable, DialectFactory.getDefaultDialect());
  }

  public Delete(Table paramTable, Dialect paramDialect)
  {
    this(paramTable, null, paramDialect);
  }

  public Delete(Table paramTable, Where paramWhere, Dialect paramDialect)
  {
    super(paramTable, paramDialect);
    setWhere(paramWhere);
  }

  public void setWhere(Where paramWhere)
  {
    this.where = paramWhere;
  }

  public Where getWhere()
  {
    return this.where;
  }

  public PreparedStatement createPreparedStatement(Connection paramConnection)
    throws SQLException
  {
    if (paramConnection == null)
    {
      FRContext.getLogger().log(Level.WARNING, "Connection can not be null.");
      return null;
    }
    if (getTable() == null)
    {
      FRContext.getLogger().log(Level.WARNING, "Table can not be null");
      return null;
    }
    if ((!(isEmptyWhereAllowed())) && (this.where == null))
    {
      FRContext.getLogger().log(Level.WARNING, "Where can not be null");
      return null;
    }
    String str = TemplateUtils.render("DELETE FROM ${table} ${where}", new String[] { "table", "where" }, new String[] { getTable().toStatementSQLString(this.dialect), (this.where == null) ? "" : this.where.toStatementSQLString(this.dialect) });
    FRContext.getLogger().log(Level.INFO, str.toString());
    PreparedStatement localPreparedStatement = paramConnection.prepareStatement(str);
    if (this.where != null)
      this.where.applyColumnTypeValue(this.dialect, paramConnection, getTable(), localPreparedStatement, 1);
    return localPreparedStatement;
  }

  public int execute(Connection paramConnection)
    throws SQLException
  {
    PreparedStatement localPreparedStatement = createPreparedStatement(paramConnection);
    try
    {
      if (localPreparedStatement != null)
      {
        int i = localPreparedStatement.executeUpdate();
        return i;
      }
    }
    finally
    {
      DBUtils.closeStatement(localPreparedStatement);
    }
    return 0;
  }
}